package test;

/*
 * Author: JacksonCoder
 * FileName: streamDemo
 * Version: 1.0.0
 * Date: 2025/5/10
 */

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class streamDemo {

    public static void main(String[] args) {

        // 过滤 filter
        List<Integer> ages = Arrays.asList(12,15,13,19,17,18);
        List<Integer> adults = ages.stream()
                .filter(age -> age > 18)
                .collect(Collectors.toList());
        System.out.println(adults);

        //  映射 map
        List<String> words = Arrays.asList("apple","banana","kiwi");
        List<Integer> lengths = words.stream()
                .map(String::length)
                .collect(Collectors.toList());
        System.out.println(lengths);

        // 聚合 reduce
        List<Integer> nums = Arrays.asList(1,2,4,5,6);
        int sum = nums.stream()
                .reduce(0,Integer::sum);
        System.out.println(sum);

        // 排序
        List<Integer> list = Arrays.asList(1,2,3,4);
        List<Integer> sortedList = list.stream()
                .sorted()
                .collect(Collectors.toList());
        System.out.println("sorted before: " + sortedList);

        // 去重 distinct
        List<Integer> nums1 = Arrays.asList(1, 2, 2, 3, 3, 3, 4);
        List<Integer> unique = nums1.stream()
                .distinct()
                .collect(Collectors.toList());
        System.out.println(unique); // 输出: [1, 2, 3, 4]

        // 收集 collect
        List<String> names = Arrays.asList("Tom","Jerry","Alen","Alice","Tom","Alen");
        Set<String> nameSet = names.stream()
                .collect(Collectors.toSet());
        System.out.println(nameSet);

        // 分组 grouping By 类似 SQL的 group by
        List<String> wordArrays = Arrays.asList("apple","ant","banana","blueberry","watermelon","cherry","pear");
        Map<Character,List<String>> grouped = wordArrays.stream()
                .collect(Collectors.groupingBy(word -> word.charAt(0)));
        System.out.println(grouped);
    }

}
